package com.mooc.lib_user.ui.user

import com.alibaba.android.arouter.launcher.ARouter
import com.mooc.lib_common.CommonApp
import com.mooc.lib_common.action.BusAction
import com.mooc.lib_common.action.BusConst
import com.mooc.lib_common.arouter.service.UserLoginAService
import com.mooc.lib_common.model.UserEntity
import com.mooc.lib_common.mvvm.BaseFragment
import com.mooc.lib_network.imgload.ImageLoad
import com.mooc.lib_user.BR
import com.mooc.lib_user.R
import com.mooc.lib_user.databinding.FragmentMyBinding
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class UserFragment : BaseFragment<UserViewModel,FragmentMyBinding>(){

    override fun initView() {
        v.setVariable(BR.vm,vm)
    }

    override fun bindLayout(): Int {
        return R.layout.fragment_my
    }

    override fun initData() {
        EventBus.getDefault().register(this)
        bindBus()
        //未登录
        val isLogin : Boolean = (ARouter.getInstance().build("/lib_user/UserLoginService").
        navigation() as UserLoginAService).isLogin()
        if (!isLogin){
            ARouter.getInstance().build("/lib_user/LoginActivity").
            navigation()
            return
        }
        //已登陆
        val userEntity = (ARouter.getInstance().build("/lib_user/UserLoginService").
        navigation() as UserLoginAService).getUser()
        vm.requestUser(userEntity!!.userId)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun refreshLogin(action : BusAction){
        if (action.action.equals(BusConst.LOGINACTION)){
            refreshView(CommonApp.userEntity!!)
        }
    }

    fun bindBus(){
        vm.userBus.observe(this,{
            if (it == null)
                return@observe
            refreshView(it)
        })
    }

    //刷新界面下的数据
    fun refreshView(entity: UserEntity){
        ImageLoad.loadMatch(entity.avatar,v.userHeadImg)
        ImageLoad.loadMatch(entity.avatar,v.avatar)
        v.name.setText(entity.name)
        v.description.setText(entity.description)
        v.likeCount.setText(""+entity.likeCount)
        v.fansCount.setText(""+entity.followCount)
        v.followCount.setText(""+entity.followCount)
        v.scoreCount.setText(""+entity.historyCount)

    }

}